import React, { useState, useEffect, useRef, useContext } from 'react'
import { Button, Table, Modal, Form, Input } from 'antd'
import { geCategory, editCategory, deleteCatgory ,addCatgory} from '../../../api/Article-manageApi'
import { DeleteOutlined, ExclamationCircleOutlined } from '@ant-design/icons'
const { confirm } = Modal
export default function NewsCategory() {
    const [dataSource, setdataSource] = useState([])
    const [artTite, setartTite] = useState()
    // 模态框显示状态
    const [isModalOpen, setIsModalOpen] = useState(false);
    // 获取文章类型列表
    useEffect(() => {
        getList()
    }, [])
    // 获取数据列表
    const getList = () => {
        geCategory().then((res) => {
            setdataSource(res.categoryList)
        })
    }
    // 修改栏目名称回调
    const handleSave = (record) => {
        console.log(record);
        setdataSource(dataSource.map(item => {
            if (item.categoryId === record.categoryId) {
                return {
                    categoryId: item.categoryId,
                    title: record.title,
                    value: record.title
                }
            }
            return item
        }))
        // 提交修改到后端
        editCategory({
            categoryId: record.categoryId,
            title: record.title,
            value: record.title
        })
    }
    // 表头
    const columns = [
        {
            title: 'ID',
            dataIndex: 'categoryId',
            render: (categoryId) => {
                return <b>{categoryId}</b>
            }
        },
        {
            title: '栏目名称',
            dataIndex: 'title',
            onCell: (record) => ({
                record,
                editable: true,
                dataIndex: 'title',
                title: '栏目名称',
                handleSave: handleSave,
            }),

        },
        {
            title: "操作",
            render: (item) => {
                return <div>
                    <Button danger shape="circle" icon={<DeleteOutlined />} onClick={() => confirmMethod(item)} />
                </div>
            }
        }
    ];

    // 删除回调
    const confirmMethod = (item) => {
        confirm({
            title: '你确定要删除?',
            icon: <ExclamationCircleOutlined />,
            // content: 'Some descriptions',
            onOk() {
                //   console.log('OK');
                deleteMethod(item)
            },
            onCancel() {
                //   console.log('Cancel');
            },
        });

    }
    //删除操作
    const deleteMethod = (item) => {
        // console.log(item)
        // 当前页面同步状态 + 后端同步
        setdataSource(dataSource.filter(data => data.categoryId !== item.categoryId))
        deleteCatgory(item.categoryId)
    }
    const EditableContext = React.createContext(null);
    // 编辑行回调
    const EditableRow = ({ index, ...props }) => {
        const [form] = Form.useForm();
        return (
            <Form form={form} component={false}>
                <EditableContext.Provider value={form}>
                    <tr {...props} />
                </EditableContext.Provider>
            </Form>
        );
    };
    const EditableCell = ({
        title,
        editable,
        children,
        dataIndex,
        record,
        handleSave,
        ...restProps
    }) => {
        const [editing, setEditing] = useState(false);
        const inputRef = useRef(null);
        const form = useContext(EditableContext);
        useEffect(() => {
            if (editing) {
                inputRef.current.focus();
            }
        }, [editing]);

        const toggleEdit = () => {
            setEditing(!editing);
            form.setFieldsValue({
                [dataIndex]: record[dataIndex],
            });
        };

        const save = async () => {
            try {
                const values = await form.validateFields();
                toggleEdit();
                handleSave({ ...record, ...values });
            } catch (errInfo) {
                console.log('Save failed:', errInfo);
            }
        };

        let childNode = children;

        if (editable) {
            childNode = editing ? (
                <Form.Item
                    style={{
                        margin: 0,
                    }}
                    name={dataIndex}
                    rules={[
                        {
                            required: true,
                            message: `${title} is required.`,
                        },
                    ]}
                >
                    <Input ref={inputRef} onPressEnter={save} onBlur={save} />
                </Form.Item>
            ) : (
                <div
                    className="editable-cell-value-wrap"
                    style={{
                        paddingRight: 24,
                    }}
                    onClick={toggleEdit}
                >
                    {children}
                </div>
            );
        }

        return <td {...restProps}>{childNode}</td>;
    };
    // 控制添加模态框显示
    const showModal = () => {
        setIsModalOpen(true);
        setartTite(null)
    };
     
    const handleOk = () => {
        setIsModalOpen(false);
        console.log(artTite);
        addCatgory({
            title: artTite,
            value:artTite
        }).then((res) => {
            getList()
        })

    };
    // 控制添加模态框隐藏
    const handleCancel = () => {
        setIsModalOpen(false);
    };
    return (
        <div>
            <Button
                style={{ margin: '0 0 10px 0' }}
                type="primary"
                onClick={showModal}
            >添加类型</Button>
            {/* 新增的弹框 */}
            <Modal title="添加文章类型" open={isModalOpen} onOk={handleOk} onCancel={handleCancel}>
                <Input placeholder="请输入文章类型" value={artTite} onChange={ (a) => {setartTite(a.target.value);}} />
            </Modal>
            <Table dataSource={dataSource} columns={columns}
                pagination={{
                    pageSize: 5
                }}
                rowKey={item => item.categoryId}

                components={{
                    body: {
                        row: EditableRow,
                        cell: EditableCell,
                    }
                }}

            />
        </div>
    )
}
